/**
 * 
 */
package com.wisdytech.linkdcs.equipment.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.wisdytech.linkdcs.equipment.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.equipment.model.CollectionClient;
import com.wisdytech.linkdcs.equipment.model.CollectionParam;
import com.wisdytech.linkdcs.equipment.model.EquipModel;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.model.ModelOperation;
import com.wisdytech.linkdcs.equipment.service.IEquipmentModelService;
import com.wisdytech.linkdcs.equipment.service.IModelOperationService;
import com.wisdytech.linkdcs.system.dao.ISysDictDao;
import com.wisdytech.linkdcs.system.model.SysDict;

/**
 * <p>
 * ClassName: EquipmentModelServiceImpl
 * </p>
 * <p>
 * Description: 设备类别表的业务实现类
 * </p>
 * <p>
 * Author: kongming
 * </p>
 * <p>
 * Date: 2017-9-26
 * </p>
 */
@Service("equipmentModelService")
@Transactional
public class EquipmentModelServiceImpl extends BaseService<IEqModelDao, EquipModel> implements IEquipmentModelService{
    /**
     * 注入设备类别dao
     */
    @Resource
    private IEqModelDao eqModelDao;
    /**
     * 注入采集表dao
     */
    @Resource
    private IEqCollectionClientDao eqCollectionClientDao;
    /**
     * 注入设备Dao
     */
    @Resource
    private IEqEquipmentDao eqEquipmentDao;
    
    /**
     * 注入采集器参数eqCollectionParamDao
     */
    @Resource
    private IEqCollectionParamDao eqCollectionParamDao;
    
    @Autowired
    private IModelOperationService iModelOperationService;
    @Autowired
    private ISysDictDao iSysDictDao;
    @Autowired
    private IModelOperationDao iModelOperationDao;
    @Override
    public PageInfo<EquipModel> listModelByFilter(String emModel, String emModelType, Filter filter) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("emModel", emModel);
        queryMap.put("emModelType", emModelType);
        List<EquipModel> lists =
                super.beforeList(IEqModelDao.class, filter).selectParamPage(queryMap);
        PageInfo<EquipModel> equipModelPage=new PageInfo<>(lists);
        
        //补充工序
        
        for(EquipModel em :equipModelPage.getList()){
        	List<ModelOperation> mos =
        			iModelOperationService.listOperations(em.getModelCode());
        	em.setOperationList(mos);
        }
        
        
        return equipModelPage;
    }
    
    @Override
    public StandardResult addModel(EquipModel model, String loginName) {
        EntityWrapper<EquipModel> ew =new EntityWrapper<>();
        //验证设别类别编号的唯一性
        List<EquipModel> modelList;
        modelList = eqModelDao.selectPage(new Page<EquipModel>(1, 1), ew.eq("MODEL_CODE", model.getModelCode()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!modelList.isEmpty()) {
            return StandardResult.getFailResult(CommonConstants.EM_MODEL);
        }
        model.setPkId(BaseUtil.getUUID());
        model.setDelFlag(CommonConstants.DEL_FLAG);
        model.setCreateUser(loginName);
        model.setCreateDate(new Date());

        
    	 CollectionClient client = new CollectionClient();
		 client.setModelCode(model.getModelCode());
         client.setCode(model.getCode());
         
         client.setPkId(BaseUtil.getUUID()   );
         client.setDelFlag(CommonConstants.DEL_FLAG);
         client.setCreateUser(loginName);
         client.setCreateDate(new Date());
         client.setType(model.getCollectionType());
         eqCollectionClientDao.insert(client);
       
         
         //增加工序
         if(null != model.getOperationId()) {
        	 
        	 List<ModelOperation>  mos =new ArrayList<>();
        	 for(String opId : model.getOperationId()) {
        		 ModelOperation mo =new ModelOperation();
        		 mo.setPkId(BaseUtil.getUUID());
        		 mo.setModelCode(model.getModelCode());
        		 mo.setOpId(opId);
        		 mos.add(mo);
        	 }
        	 
        	 iModelOperationService.add(mos);
         }
         
         
         
         

        int count = eqModelDao.insert(model);
       
        if (count <=0 ) {
            throw new ServiceException("新增失败");
        }
        
        
        
        
        
        return StandardResult.getSuccessResult();
    }
    @Override
    public StandardResult delModel(String id) {
        List<String> idList = new ArrayList<String>();
        String[] pkIds = id.split(",");
//        List<Equipment> eqEquipmentList = new ArrayList<Equipment>();
        EntityWrapper<Equipment> ewEquipment = new EntityWrapper<>();
        List<CollectionClient> collectClientList;
        
        
        for (String pkId : pkIds) {
			EquipModel model = eqModelDao.selectById(pkId);
            int equipmentCount = 
            		eqEquipmentDao.selectCount(ewEquipment.eq("MODEL_CODE", model.getModelCode()).eq("del_flag", CommonConstants.DEL_FLAG));

            if (equipmentCount>0) {
                return StandardResult.getFailResult(CommonConstants.EQUIP_MODEL_DEL);
            }
            
            EntityWrapper<CollectionClient> ewClient = new EntityWrapper<>();
            collectClientList = eqCollectionClientDao.selectList(ewClient.eq("MODEL_CODE", model.getModelCode()));
            //删除设备类别--先删除对应的设备采集参数
            for (CollectionClient cc : collectClientList) {
                EntityWrapper<CollectionParam> ewParam = new EntityWrapper<>();
                int paramCount = eqCollectionParamDao.delete(ewParam.eq("COLLECTION_CLIENT_ID", cc.getPkId()));
                if (paramCount <0){
                    throw new ServiceException("删除失败");
                }
            }
            //删除设备类别--再删除对应的设备采集器
           int clientCount = eqCollectionClientDao.delete(ewClient);
           if (clientCount <0){
               throw new ServiceException("删除失败");
           }
        }
        for (int i = 0; i < pkIds.length; i++) {
            idList.add(pkIds[i]);
        }
        //删除设备类别--最后删除设备类别
        int modelCount = eqModelDao.deleteBatchIds(idList);
        if (modelCount <= 0 ) {
            throw new ServiceException("删除失败");
        }
        return StandardResult.getSuccessResult();
    }
    
    @Override
    public StandardResult updateModel(EquipModel model,String loginName) {
        //验证设备类别编号的唯一性--修改功能
        EntityWrapper<EquipModel> ewModel = new EntityWrapper<>();
        List<EquipModel> modelList;
        modelList = eqModelDao.selectPage(new Page<Equipment>(1, 1),ewModel.eq("MODEL_CODE", model.getModelCode()).ne("pk_id", model.getPkId()));
        if (modelList.size() > 0){
            return StandardResult.getFailResult(CommonConstants.EM_MODEL);
        }
        model.setUpdateDate(new Date());
        model.setUpdateUser(loginName);
        int modelCount = eqModelDao.updateById(model);
        EntityWrapper<CollectionClient> ewClient = new EntityWrapper<>();

        EquipModel m = eqModelDao.selectById(model.getPkId());
        //修改类型
        List<CollectionClient> clients;
        clients = eqCollectionClientDao.selectList(ewClient.eq("model_code", m.getModelCode()));
        for (CollectionClient client : clients) {
            //判断改型号下是否有参数
            EntityWrapper<CollectionParam> ew = new EntityWrapper();
            ew.eq("COLLECTION_CLIENT_ID",client.getPkId());
            ew.eq("DEL_FLAG",CommonConstants.DEL_FLAG);
            List<CollectionParam> list = eqCollectionParamDao.selectList(ew);
            if(!list.isEmpty()){
                throw new ServiceException("该型号下已有参数，不允许修改");
            }
			client.setModelCode(m.getModelCode());
            client.setCode(model.getCode());
//            client.setEcRoute(model.getEcRoute());
            client.setUpdateDate(new Date());
            client.setUpdateUser(loginName);
            client.setDelFlag(CommonConstants.DEL_FLAG);
            client.setType(model.getCollectionType());
            int clientCount = eqCollectionClientDao.updateById(client);
            if (modelCount<=0 || clientCount<=0) {
                throw new ServiceException("修改失败");
            }
        }
        
        //删除全部工序

        iModelOperationService.del(m.getModelCode());
        
        //增加工序
        if(null != model.getOperationId()) {
       	 
       	 List<ModelOperation>  mos =new ArrayList<>();
       	 for(String opId : model.getOperationId()) {
       		 ModelOperation mo =new ModelOperation();
       		 mo.setPkId(BaseUtil.getUUID());
       		 mo.setModelCode(m.getModelCode());
       		 mo.setOpId(opId);
       		 mos.add(mo);
       	 }
       	 
       	 iModelOperationService.add(mos);
        }

        return StandardResult.getSuccessResult();
    }
    @Override
    public EquipModel getEuipmentModelById(String pkId) {
    	
    	EquipModel  model =
    			eqModelDao.getEuipmentModelById(pkId);
    	
    	//补充工序信息
    	List<ModelOperation> operations = iModelOperationService.listOperations(model.getModelCode());
    	model.setOperationList(operations);
    	
    	
        return model;
    }
    @Override
    public EquipModel getEuipmentModelByEmModel(String emModel) {
    	EquipModel  model =eqModelDao.getEuipmentModelByEmModel(emModel);
    	//补充工序信息
        if(model!=null){
            List<ModelOperation> operations = iModelOperationService.listOperations(model.getModelCode());
            model.setOperationList(operations);
        }
        return model;
    }
    @Override
    public List<EquipModel> listAllModel(String serach) {
        EntityWrapper<EquipModel> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(serach)) {
            ew.like("MODEL_CODE", serach);
        }
        List<EquipModel> equipModelList = eqModelDao.selectList(ew);
        return equipModelList;
    }
    @Override
    public List<EquipModel> listParamByEmModel(String emModel) {
        return eqModelDao.listParamByEmModel(emModel);
    }
    
    
    private List<Integer> getCollectionTypes(String typeStrs){
    	List<Integer> types =new ArrayList<Integer>();
         String [] typeArrs=typeStrs.split(",");
         for(String typeStr :typeArrs){
        	 types.add(Integer.parseInt(typeStr));
         }
         
         return types;
    }

	@Override
	public List<EquipModel> listAllSupplier(String search) {
        EntityWrapper<EquipModel> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(search)) {
            ew.like("SUPPLIER", search);
        }
        List<EquipModel> equipModelList = eqModelDao.selectList(ew);
        return equipModelList;
	}

	@Override
	public List<EquipModel> listAllModelType(String search) {
        EntityWrapper<EquipModel> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(search)) {
            ew.like("MODEL_TYPE", search);
        }
        List<EquipModel> equipModelList = eqModelDao.selectList(ew);
        return equipModelList;
	}

	@Override
	public List<SysDict> getSupplier(String search) {
		EntityWrapper<SysDict> ew  = new EntityWrapper<>();
		ew.eq("PARENT_KEY", "SUPPLIER");
		if(StringUtils.isNotEmpty(search)) {
			ew.like("DICT_VALUE", search);
		}
		return iSysDictDao.selectList(ew);
	}
}
